<?php
namespace Admin\Controller;

use Think\Exception;
use Think\Model;

/**
 * Class 店铺可售货品
 * @package Admin\Controller
 */
class StoreGoodsController extends BaseController
{

    public function index()
    {
        $local_id= session("userInfo")['local_id'];

        $name = I('name', '', htmlspecialchars()); // 货品名称

        if (!empty($name)) {
            $where['b.name'] = array('like',"%$name%");
            $this->assign('name', $name);
        }

        // 条码
        if (isset($_GET['barcode']) && !empty($_GET['barcode'])) {
            $barcode = I('barcode');
            $where['b.barcode'] = ['like', "%$barcode%"];
            $this->assign('barcode', $barcode);
        }

        $store_status = I('store_status', '', htmlspecialchars()); // 店铺商品上架true、下架false筛选
        if (!empty($store_status)) {
            if ($store_status == 'false') {
                $left_join_store_product = "b2c_store_product c on a.product_id=c.product_id AND c.local_id = $local_id and  c.store_status <> 'true'";
            }else {
                $where['c.store_status'] = $store_status;
                $left_join_store_product = "b2c_store_product c on a.product_id=c.product_id AND c.local_id = $local_id";
            }
        } else {
            $left_join_store_product = "b2c_store_product c on a.product_id=c.product_id AND c.local_id = $local_id";
        }

        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 15);

        $order = "b.product_id desc";

        $where['a.product_type_id'] = 1;
        $where['b.disabled'] = 'false';
        $where['b.is_qgs_show'] = '0';

        $field = "b.*,a.guidance_price,c.store_status,c.explain,c.store_pid,c.local_id";

        // 可售货品
        $b2c_products = M('b2c_products b');
        $count = $b2c_products
            ->join(C('DB_PREFIX') . 'b2c_product_relation a on a.product_id=b.product_id', 'left')
            ->join(C('DB_PREFIX') . $left_join_store_product, 'left')
            ->where($where)
            ->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        /**
         * sql:
        SELECT
        b.*, a.guidance_price,
        c.store_status,
        c.`explain`,
        c.store_pid,
        c.local_id
        FROM
        sdb_b2c_products b
        LEFT JOIN sdb_b2c_product_relation a ON a.product_id = b.product_id
        LEFT JOIN sdb_b2c_store_product c ON a.product_id = c.product_id
        AND c.local_id = 1
        WHERE
        a.product_type_id = 1
        AND b.disabled = 'false'
        AND b.is_qgs_show = '0'
        LIMIT 0,
        15
         */
        $product_relation_msg = $b2c_products
            ->join(C('DB_PREFIX') . 'b2c_product_relation a on a.product_id=b.product_id', 'left')
            ->join(C('DB_PREFIX') . $left_join_store_product, 'left')
            ->where($where)
            ->field($field)
            ->order($order)
            ->page($page, $num)
            ->select();
//echo $b2c_products->_sql();
        $this->assign([
            'product_relation_msg' => $product_relation_msg,
            'show' => $show
        ]);

        // 商品分类
        $catModel = M('b2c_store_cat');
        $parent = $catModel->where(['level' => 1, 'local_id' => session("userInfo")['local_id']])->select();
        $second = $catModel->where(['level' => 2, 'local_id' => session("userInfo")['local_id']])->select();
//        $three = $catModel->where(['level' => 3, 'local_id' => session("userInfo")['local_id']])->select();

        $this->assign(['parent' => $parent, 'second' => $second]);

        $this->display();
    }

    // 上架商品管理
    public function putaway(){
        $local_id= session("userInfo")['local_id'];

        $name = I('name', '', htmlspecialchars()); // 货品名称

        if (!empty($name)) {
            $where['b.name'] = array('like',"%$name%");
            $this->assign('name', $name);
        }

        // 条码
        if (isset($_GET['barcode']) && !empty($_GET['barcode'])) {
            $barcode = I('barcode');
            $where['b.barcode'] = ['like', "%$barcode%"];
            $this->assign('barcode', $barcode);
        }

        // 分类
        if (isset($_GET['cat_id']) && !empty($_GET['cat_id'])){
            $cat_id = I('cat_id');
            $where['c.scate_id'] = $cat_id;
            $this->assign('cat_id', $cat_id);
        }

        $where['c.store_status'] = "true";
        $left_join_store_product = "b2c_store_product c on a.product_id=c.product_id AND c.local_id = $local_id";

        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 15);

        $order = "p_relation_id desc";
        $product_relation_model = M('b2c_product_relation a');

        $where['a.product_type_id'] = 1;
//        $where['b.disabled'] = 'false';

        $field = "b.*,a.guidance_price,c.store_status,c.explain,c.store_pid,c.local_id";

        // 可售货品
        $count = $product_relation_model
            ->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id AND b.disabled = "false"', 'left')
            ->join(C('DB_PREFIX') . $left_join_store_product, 'left')
            ->where($where)
            ->count();
//        echo $product_relation_model->_sql();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $product_relation_msg = $product_relation_model
            ->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id AND b.disabled = "false"', 'left')
            ->join(C('DB_PREFIX') . $left_join_store_product, 'left')
            ->where($where)
            ->order($order)
            ->field($field)
            ->page($page, $num)
            ->select();
//echo $product_relation_model->_sql();
        $this->assign([
            'product_relation_msg' => $product_relation_msg,
            'show' => $show
        ]);

        // 商品分类
        $catModel = M('b2c_store_cat');
        $parent = $catModel->where(['level' => 1, 'local_id' => session("userInfo")['local_id']])->select();
        $second = $catModel->where(['level' => 2, 'local_id' => session("userInfo")['local_id']])->select();

        $this->assign(['parent' => $parent, 'second' => $second]);

        $this->display();
    }


    /**
     * 添加商品
     */
    public function addGoods(){

        $flag = 'false';
        $data_msg = '保存完成';
        $data = I('data', '', htmlspecialchars());

        $m = M('b2c_store_product');
        $b2c_products_model = M('b2c_products');

        if (!empty($data)) {
            get_curl(session('userInfo')['local_id']);
            foreach ($data as $v) {
                $p_relation_id_arr = explode('#', $v);
                $p_relation_id_arr[7] = urldecode($p_relation_id_arr[7]);

                $b2c_products =$b2c_products_model->where(['product_id' => $p_relation_id_arr[0], 'disabled' => 'false'])->find(); // 查询基本货品表信息

                $b2c_goods = M('b2c_goods')->where(['goods_id' => $b2c_products['goods_id'], 'disabled' => 'false'])->find();

                $store_products_msg = $m->where(['product_id' => $p_relation_id_arr[0], 'local_id' => session('userInfo')['local_id']])->find(); // 查询店铺货品

                if ($p_relation_id_arr[3] < $store_products_msg['freez']){
                    $this->error('店铺库存不能小于冻结库存');
                }

                try{
                    M()->execute('begin');

                    // 判断数组第6个元素为0删除店铺货品
                    if ($p_relation_id_arr[5] == 0) {
                        // $p_relation_id_arr[0] 表示删除
                        if ($store_products_msg) {
                            $store_goods = $m->field('store_pid')->where(['product_id' => $p_relation_id_arr[0], 'local_id' => session('userInfo')['local_id'], 'store_status' => 'true'])->find();
                            if ($store_goods) {
                                // 判断店铺商品是否在订单促销中就不能删除
                                if (goods_is_Order_promotion($store_goods['store_pid'], session('userInfo')['local_id']) == true) {
                                    throw new \Exception("商品在订单促销中就不能删除");
                                }
                                // 判断店铺商品是否在订单促销中就不能删除
                                if (goods_is_Goods_promotion($store_goods['store_pid'], session('userInfo')['local_id']) == true) {
                                    throw new \Exception("商品在商品促销中就不能删除");
                                }
                                // 判断店铺商品是否在闪购中就不能删除
                                if (goods_is_shangou($store_goods['store_pid'], session('userInfo')['local_id']) == true) {
                                    throw new \Exception("店铺商品在闪购中就不能删除");
                                }
                                // 判断店铺商品在组合商品中就不能删除
                                if (checkProductIsGroupPromotion($store_goods['store_pid'], session('userInfo')['local_id']) == true) {
                                    throw new \Exception("店铺商品在组合商品中就不能删除");
                                }

                                // 判断商品在专题中
                                if (checkProductIsSpecial($store_goods['store_pid'], session('userInfo')['local_id']) == true) {
                                    throw new \Exception("商品在专题中不能删除");
                                }
                                $delete = $m->where(['product_id' => $p_relation_id_arr[0], 'local_id' => session('userInfo')['local_id']])->save(['store_status' => 'false']);
                                if ($delete == false) {
                                    throw new \Exception('删除商品失败');
                                }
                            }

                        }
                    } else { // 如果数组第6个元素不为0就表示已经存在或者准备添加的店铺商品，就添加或者更新
                        if (!empty($store_products_msg)) {  // 更新已有店铺商品

                            $add_data = [
                                'price' => $p_relation_id_arr[2],
                                'marketprice' => $p_relation_id_arr[1],
                                'discount' => $p_relation_id_arr[4],
                                'store' => $p_relation_id_arr[3],
                                'scate_id' => $p_relation_id_arr[6],
                                'bn' => $p_relation_id_arr[7],
                                'store_status' => 'true',
                                'is_transport' => $p_relation_id_arr[8],
                                'explain' => $p_relation_id_arr[9],
                                'p_name' => $b2c_goods['name']
                            ];
                            $save = $m->where(['local_id' => session('userInfo')['local_id'], 'product_id' => $b2c_products['product_id']])->save($add_data);
                            if ($save === false) {
                                throw new \Exception("服务器异常");
                            }
                        } else { // 添加店铺商品
                            $add_data = [
                                'local_id' => session('userInfo')['local_id'],
                                'product_id' => $b2c_products['product_id'],
                                'goods_id' => $b2c_products['goods_id'],
                                'price' => $p_relation_id_arr[2], // 销售价格
                                'marketprice' => $p_relation_id_arr[1], //市场价格
                                'discount' => $p_relation_id_arr[4], // 折后价格
                                'store' => $p_relation_id_arr[3], // 库存
                                'scate_id' => $p_relation_id_arr[6], // 商品分类
                                'bn' => $p_relation_id_arr[7], // 货号
                                'store_status' => 'true',
                                'is_transport' => $p_relation_id_arr[8], // 是否快递
                                'explain' => $p_relation_id_arr[9],
                                'p_name' => $b2c_goods['name']
                            ];
                            $add = $m->add($add_data);
                            if ($add === false) {
                                throw new \Exception("服务器异常");
                            }
                        }
                    }

                    M()->execute('commit');
                    $flag = 'true';
                }catch(\Exception $e){
                    M()->execute('rollback');
                    $data_msg = $e->getMessage();
                    $flag = 'false';
                }
            }
        }
        echo json_encode(['status' => $flag, 'msg' => $data_msg]);
    }

    /**
     * 标签
     */
    public function label(){
        $id = I('id', '', intval());
        $local_id = session('userInfo')['local_id'];
        $product = M('store_products_label_relation b')
            ->join('sdb_b2c_store_product a on a.product_id = b.product_id', 'left')
            ->where(['a.product_id' => $id, 'a.local_id' => session('userInfo')['local_id']])
            ->field(['b.label_id'])
            ->select();
        $label = M('store_products_label')->where(['local_id' => $local_id])->select();

        foreach ($product as $v) {
            $arr[] = $v['label_id'];
        }

        $this->assign(['product_label' => $arr, 'label' => $label, 'id' => $id]);
        $this->display();
    }

    /**
     * 保存标签
     *
     */
    public function labelSave(){
        if ($_POST) {
            $id = I('id', '', intval());
            $label = I('label', '', htmlspecialchars());
            $store_products_label_relation = M('store_products_label_relation');

            $where = [
                'product_id' => $id,
                'local_id' => session('userInfo')['local_id'],
            ];


            $model = new Model();
            try{
                $model->startTrans();

                $store_products_label_relation->where($where)->delete();

                foreach ($label as $v) {
                    $data = [
                        'label_id' => $v,
                        'local_id' => session('userInfo')['local_id'],
                        'product_id' => $id,
                    ];
                    $add = $store_products_label_relation ->add($data);
                    if ($add === false) {
                        throw new Exception("error");
                    }
                }
                $model->commit();

            }catch (Exception $e){
                $model->rollback();
            }

            $this->success('完成');
        }
    }

    /**
     * 导出可上架商品
     */
    public function excel(){
        $local_id= session("userInfo")['local_id'];

        $where['c.store_status'] = "true";
        $left_join_store_product = "b2c_store_product c on a.product_id=c.product_id AND c.local_id = $local_id";

        $order = "p_relation_id desc";
        $product_relation_model = M('b2c_product_relation a');

        $where['a.product_type_id'] = 1;
        $field = "b.name,b.barcode,b.spec_info,c.price,c.store,b.unit,d.cat_name";
        $product_relation_msg = $product_relation_model
            ->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id AND b.disabled = "false"', 'left')
            ->join(C('DB_PREFIX') . $left_join_store_product, 'left')
            ->join(C('DB_PREFIX') . 'b2c_store_cat d on c.scate_id=d.store_cat_id', 'left')
            ->where($where)
            ->order($order)
            ->field($field)
            ->select();
        foreach ($product_relation_msg as $k=>$v) {
            $arr[$k][] = ' '.$v['name'];
            $arr[$k][] = ' '.$v['barcode'];
            $arr[$k][] = ' '.$v['spec_info'];
            $arr[$k][] = ' '.$v['price'];
            $arr[$k][] = ' '.$v['store'];
            $arr[$k][] = ' '.$v['unit'];
            $arr[$k][] = ' '.$v['cat_name'];
        }
//        var_dump($arr);
        $xlsName  = "怡臣电子商务-上架商品";
        $xlsCell  = array(
            array('0','商品名称'),
            array('1','条码'),
            array('2','货品描述'),
            array('3','价格'),
            array('4','库存'),
            array('5','单位'),
            array('6','分类'),
        );
//        var_dump($xlsCell);exit;
        exportExcel($xlsName,$xlsCell,$arr);exit;
    }

}